package com.ytzl.itrip.utils.common;

import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;

/**
 * Created by asus on 2018/7/17.
 */
@Component
public class SendMail {

    @Resource
    private RedisAPI redisAPI;


    /**
     *
     * @param receive   收件人地址
     * @throws AddressException
     * @throws MessagingException
     */
    public void send(String receive) throws MessagingException {

        /*** 账户激活码 ***/
        String code = ""+DigestUtil.randomCode();
        String code1 = DigestUtil.hmacSign(code,"itrip");
        /*** 1.得到Session ***/
        Properties props=new Properties();
        props.setProperty("mail.host", "smtp.163.com");//设置邮件服务器地址
        props.setProperty("mail.smtp.auth", "true");   //设置邮件服务器是否需要登录认证
        Authenticator auth=new Authenticator(){        //创建认证器
            public PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication("13721898650@163.com","wang8650");  //用户名和密码
            }
        };
        Session session=Session.getInstance(props,auth);  //获取Session对象

        /*** 2.创建邮件对象MimeMessage ***/
        MimeMessage msg=new MimeMessage(session);             //创建邮件对象
        msg.setFrom(new InternetAddress("13721898650@163.com")); //设置发件人
        msg.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receive)); //设置收件人
        // msg.addRecipient(RecipientType.CC, new InternetAddress("李四@qq.com"));  //设置收件人（抄送）
        // msg.addRecipient(RecipientType.BCC, new InternetAddress("王五@163.com"));//设置收件人（暗送）

        msg.setSubject("欢迎注册itrip爱旅行");                   //设置发送的邮件的标题
        msg.setContent("您账户的激活码是"+code1+"3分钟内有效。","text/html;charset=utf-8"); //指定邮件内容，以及内容的MIME类型

        /*** 3.发送邮件 ***/
        Transport.send(msg);
        redisAPI.set("mailCode:["+receive+"]",code1,60*3);

    }
}
